// src/store/modules/user.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { webLogin as webLoginApi, getUserInfo } from '@/api/user';
import router from '@/router';
import { usePermissionStore } from './permission';

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '');
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || null);

    async function webLogin(loginData) {
        const response = await webLoginApi(loginData);
        token.value = response.accessToken;
        localStorage.setItem('token', response.accessToken);
        // The router guard will handle fetching user info and redirecting.
    }

    async function fetchUserInfo() {
        const response = await getUserInfo();
        userInfo.value = response;
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
        return response; // Return user info for the guard to use
    }

    async function logout() {
        const permissionStore = usePermissionStore();
        token.value = '';
        userInfo.value = null;
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        permissionStore.resetRoutes(); // Reset permission routes
        // Forcing a reload is the cleanest way to reset all state
        location.reload(); 
    }

    return { token, userInfo, webLogin, logout, fetchUserInfo };
});